package com.gxa.weixing.portal.controller;

import com.gxa.weixing.core.common.ExceptionCode;
import com.gxa.weixing.core.common.JsonResult;
import com.gxa.weixing.core.exception.BusinessException;
import com.gxa.weixing.core.pojo.Order;
import com.gxa.weixing.core.pojo.User;
import com.gxa.weixing.core.util.StringUtil;
import com.gxa.weixing.portal.service.OrderService;
import com.gxa.weixing.portal.service.UserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.math.BigDecimal;
import java.net.*;
import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.Map;

/**
 * @Author ChenJ
 * @date 2022/01/05 18:13
 **/
@RestController
@RequestMapping("/user")
@Api(value = "userController", tags = "用户(我的)的接口")
public class UserController {

    /**
     * 请求地址
     */
    private static final String HOST = "https://idcert.market.alicloudapi.com/idcard";
    /**
     * 实名认证接口的code
     */
    private static final String APPCODE = "38f25b8513334e63ba409e9fddd459fa";

    @Resource
    private UserService userService;

    @Resource
    private OrderService orderService;

    @GetMapping("/getMy")
    @ApiOperation("获取我的接口")
    @ApiImplicitParam(name = "id", value = "用户编号",required = true,dataType = "Long", paramType = "query")
    public Map<String ,Object> getMy(@RequestParam Long id) throws BusinessException  {
        // 先进行数据校验，没有用户编号则抛出异常
        if (StringUtils.isEmpty(id)){
            throw new BusinessException(ExceptionCode.NO_PARAM);
        }
        Map<String, Object> my = userService.getMy(id);
        if (my==null){
            throw new BusinessException(ExceptionCode.NO_DATA);
        }
        JsonResult jsonResult = new JsonResult();
        jsonResult.setCode("200");
        jsonResult.setMsg("成功");
        jsonResult.setData(my);
        return jsonResult.getDataMap();
    }

    @GetMapping("/autonym")
    @ApiOperation("实名认证的接口")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "name", value = "姓名",required = true,dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "idCard", value = "身份证号码",required = true,dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "id", value = "用户编号",required = true,dataType = "Long", paramType = "query")
    })
    public Map<String,Object> autonym(@RequestParam String name,@RequestParam String idCard,@RequestParam Long id) throws BusinessException {
        // 数据校验
        if (StringUtils.isEmpty(name)||StringUtils.isEmpty(idCard)){
            throw new BusinessException(ExceptionCode.NO_PARAM);
        }
        // 校验是否为身份证
        if (!StringUtil.isIDNumber(idCard)){
            throw new BusinessException(ExceptionCode.NO_ID_CARD);
        }

        try {
            String urlSend = HOST + "?idCard=" + idCard + "&name=" + URLEncoder.encode(name, "UTF-8");
            // 生成请求url
            URL url = new URL(urlSend);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setRequestProperty("Authorization", "APPCODE " + APPCODE);
            //格式Authorization:APPCODE (中间是英文空格)
            int httpCode = connection.getResponseCode();
            if (httpCode == 200) {
                String json = read(connection.getInputStream());
                System.out.println("正常请求计费(其他均不计费)");
                System.out.println("获取返回的json：");
                System.out.print(json);
            } else {
                Map<String, List<String>> map = connection.getHeaderFields();
                String error = map.get("X-Ca-Error-Message").get(0);
                if (httpCode == 400 && "Invalid AppCode `not exists`".equals(error)) {
                    System.out.println("AppCode错误 ");
                } else if (httpCode == 400 && "Invalid Url".equals(error)) {
                    System.out.println("请求的 Method、Path 或者环境错误");
                } else if (httpCode == 400 && "Invalid Param Location".equals(error)) {
                    System.out.println("参数错误");
                } else if (httpCode == 403 && "Unauthorized".equals(error)) {
                    System.out.println("服务未被授权（或URL和Path不正确）");
                } else if (httpCode == 403 && "Quota Exhausted".equals(error)) {
                    System.out.println("套餐包次数用完 ");
                } else {
                    System.out.println("参数名错误 或 其他错误");
                    System.out.println(error);
                }
            }
        } catch (MalformedURLException e) {
            System.out.println("URL格式错误");
        } catch (UnknownHostException e) {
            System.out.println("URL地址错误");
        } catch (Exception e) {
            // 打开注释查看详细报错异常信息
            e.printStackTrace();
        }
        // 实名认证成功后根据id查找到用户，然后将用户的身份证号码和真实姓名修改
        User user = userService.selecyId(id);
        if (user == null){
            throw new BusinessException(ExceptionCode.OPERATION_FAILURE);
        }
        user.setIdCard(idCard);
        user.setRealName(name);
        userService.updateById(user);
        System.out.println(user);

        JsonResult jsonResult = new JsonResult();
        jsonResult.setMsg("认证成功");
        jsonResult.setCode("200");
        return jsonResult.getDataMap();
    }

    /**
     * 读取返回结果
     * @param is
     * @return
     * @throws IOException
     */
    private static String read(InputStream is) throws IOException {
        StringBuilder sb = new StringBuilder();
        BufferedReader br = new BufferedReader(new InputStreamReader(is));
        String line;
        while ((line = br.readLine()) != null) {
            line = new String(line.getBytes(), StandardCharsets.UTF_8);
            sb.append(line);
        }
        br.close();
        return sb.toString();
    }

    @GetMapping("/bingDingPhone")
    @ApiOperation("绑定安全手机的接口")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "phone", value = "手机号",required = true,dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "code", value = "验证码",required = true,dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "id", value = "用户编号",required = true,dataType = "Long", paramType = "query")
    })
    public Map<String ,Object> bingDingPhone(@RequestParam String phone,@RequestParam String code,@RequestParam Long id) throws BusinessException {
        if (StringUtils.isEmpty(phone)||StringUtils.isEmpty(code)){
            throw new BusinessException(ExceptionCode.NO_PARAM);
        }
        if (!StringUtil.isPhoneNumber(phone)){
            throw new BusinessException(ExceptionCode.WRONG_PHONE);
        }
        userService.bangDing(phone, code, id);

        JsonResult jsonResult = new JsonResult();
        jsonResult.setCode("200");
        jsonResult.setMsg("成功");
        return jsonResult.getDataMap();
    }

    @GetMapping("/getOrder")
    @ApiOperation("获取我的订单的接口")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "status", value = "订单状态:0代付款,1待发货,2待收货,3已完成,4退款/售后",required = true,dataType = "Integer", paramType = "query"),
            @ApiImplicitParam(name = "id", value = "用户编号",required = true,dataType = "Long", paramType = "query")
    })
    public Map<String ,Object> getOrder(@RequestParam Integer status,@RequestParam Long id) throws BusinessException {
        // 先进行数据校验
        if (StringUtils.isEmpty(status)||StringUtils.isEmpty(id)){
            throw new BusinessException(ExceptionCode.NO_PARAM);
        }

        List<Map<String, Object>> order = orderService.getOrder(id, status);
        // 如果没有数据则抛出异常处理
        if (order.size()==0){
            throw new BusinessException(ExceptionCode.NO_DATA);
        }
        JsonResult jsonResult = new JsonResult();
        jsonResult.setCode("200");
        jsonResult.setMsg("成功");
        jsonResult.setData(order);
        return jsonResult.getDataMap();
    }

    @GetMapping("/getOrderDetail")
    @ApiOperation("获取订单详情的接口")
    @ApiImplicitParam(name = "id", value = "订单编号",required = true,dataType = "Long", paramType = "query")
    public Map<String ,Object> getOrderDetail(@RequestParam Long id) throws BusinessException {

        List<Map<String, Object>> orderDetail = orderService.getOrderDetail(id);
        if (orderDetail.size() == 0) {
            throw new BusinessException(ExceptionCode.WRONG_SERVER);
        }
        JsonResult jsonResult = new JsonResult();
        jsonResult.setMsg("成功");
        jsonResult.setData(orderDetail);
        return jsonResult.getDataMap();
    }

    @GetMapping("/putGoods")
    @ApiOperation("确认收货的接口")
    @ApiImplicitParam(name = "id", value = "订单编号",required = true,dataType = "Long", paramType = "query")
    public Map<String ,Object> putGoods(@RequestParam Long id) throws BusinessException {
        if (StringUtils.isEmpty(id)){
            throw new BusinessException(ExceptionCode.NO_PARAM);
        }
        Order order = orderService.selecyId(id);
        order.setStatus(3);
        JsonResult jsonResult = new JsonResult();
        jsonResult.setCode("200");
        jsonResult.setMsg("成功");
        return jsonResult.getDataMap();
    }

    @GetMapping("/getMyGold")
    @ApiOperation("获取我的金币的接口")
    @ApiImplicitParam(name = "id", value = "用户编号",required = true,dataType = "Long", paramType = "query")
    public Map<String ,Object> getMyGold(@RequestParam Long id) throws BusinessException {
        // 先进行数据校验
        if (StringUtils.isEmpty(id)){
            throw new BusinessException(ExceptionCode.NO_PARAM);
        }
        Map<String, Object> goldRecord = userService.getGoldRecord(id);
        if (goldRecord==null){
            throw new BusinessException(ExceptionCode.NO_DATA);
        }
        JsonResult jsonResult = new JsonResult();
        jsonResult.setCode("200");
        jsonResult.setMsg("成功");
        jsonResult.setData(goldRecord);
        return jsonResult.getDataMap();
    }

    @GetMapping("/getExchange")
    @ApiOperation("获取金币兑换记录的接口")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "用户编号",required = true,dataType = "Long", paramType = "query"),
            @ApiImplicitParam(name = "status", value = "状态:0待兑换,1已兑换",required = true,dataType = "Integer", paramType = "query")
    })
    public Map<String ,Object> getExchange(@RequestParam Long id,@RequestParam Integer status) throws BusinessException {
        // 先进行数据校验
        if (StringUtils.isEmpty(id) || StringUtils.isEmpty(status)){
            throw new BusinessException(ExceptionCode.NO_PARAM);
        }
        // 获取用户使用金币兑换记录
        List<Map<String, Object>> exchangeRecord = userService.getExchangeRecord(id, status);
        if (exchangeRecord.size()==0){
            throw new BusinessException(ExceptionCode.NO_DATA);
        }
        JsonResult jsonResult = new JsonResult();
        jsonResult.setCode("200");
        jsonResult.setMsg("成功");
        jsonResult.setData(exchangeRecord);
        return jsonResult.getDataMap();
    }

    @GetMapping("/getGoldByFriend")
    @ApiOperation("完成任务添加金币的接口")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "用户编号",required = true,dataType = "Long", paramType = "query"),
            @ApiImplicitParam(name = "number", value = "金币数量",required = true,dataType = "BigDecimal", paramType = "query")
    })
    public Map<String ,Object> getGoldByFriend(@RequestParam Long id,@RequestParam BigDecimal number) throws BusinessException {
        // 先数据校验
        if (StringUtils.isEmpty(id)||StringUtils.isEmpty(number)){
            throw new BusinessException(ExceptionCode.NO_PARAM);
        }
        // 完成任务添加金币
        userService.getGold(id, number);
        JsonResult jsonResult = new JsonResult();
        jsonResult.setCode("200");
        jsonResult.setMsg("成功");
        return jsonResult.getDataMap();
    }

    /*@GetMapping("/getGoldByProduct")
    @ApiOperation("购买商品奖励金币的接口")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "用户编号",required = true,dataType = "Long", paramType = "query"),
            @ApiImplicitParam(name = "pId", value = "商品编号",required = true,dataType = "IntLongeger", paramType = "query")
    })
    public Map<String ,Object> getGoldByProduct(@RequestParam Long id,@RequestParam Long pId){
        JsonResult jsonResult = new JsonResult();
        jsonResult.setMsg("成功");
        return jsonResult.getDataMap();
    }*/

/*    @GetMapping("/getBalance")
    @ApiOperation("获取我的余额的接口")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "用户编号",required = true,dataType = "Long", paramType = "query"),
            @ApiImplicitParam(name = "status", value = "提现状态 审核中(0)/成功(1)/失败(2)",dataType = "Long", paramType = "query")
    })
    public Map<String ,Object> getBalance(@RequestParam Long id,Integer status) throws BusinessException {
        // 先进行数据校验
        if (StringUtils.isEmpty(id)){
            throw new BusinessException(ExceptionCode.NO_PARAM);
        }
        List<Map<String,Object>> balanceLogList = null;
        if (StringUtils.isEmpty(status)){
            balanceLogList = userService.getBalanceLog(id);
        }else {
            balanceLogList = userService.getBalanceLogByStatus(id, status);
        }
        if (balanceLogList.size()==0){
            throw new BusinessException(ExceptionCode.NO_DATA);
        }

        JsonResult jsonResult = new JsonResult();
        jsonResult.setCode("200");
        jsonResult.setMsg("成功");
        jsonResult.setData(balanceLogList);
        return jsonResult.getDataMap();
    }*/

    @GetMapping("/getDeposit")
    @ApiOperation("获取提现记录的接口")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "用户编号",required = true,dataType = "Long", paramType = "query"),
            @ApiImplicitParam(name = "logStatus", value = "提现状态：0审核中，1成功，2失败",dataType = "Integer", paramType = "query")
    })
    public Map<String ,Object> getDeposit(@RequestParam Long id,Integer logStatus) throws BusinessException {
        // 先进行数据校验
        if (StringUtils.isEmpty(id)){
            throw new BusinessException(ExceptionCode.NO_PARAM);
        }
        List<Map<String,Object>> balanceLogList = null;
        if (StringUtils.isEmpty(logStatus)){
            balanceLogList = userService.getBalanceLog(id);
        }else {
            balanceLogList = userService.getBalanceLogByStatus(id, logStatus);
        }
        if (balanceLogList.size()==0){
            throw new BusinessException(ExceptionCode.NO_DATA);
        }

        JsonResult jsonResult = new JsonResult();
        jsonResult.setCode("200");
        jsonResult.setMsg("成功");
        jsonResult.setData(balanceLogList);
        return jsonResult.getDataMap();
    }

    @GetMapping("/getApplyDeposit")
    @ApiOperation("提现申请的接口")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "用户编号",required = true,dataType = "Long", paramType = "query"),
            @ApiImplicitParam(name = "num", value = "提现金额",required = true,dataType = "BigDecimal", paramType = "query")
    })
    public Map<String ,Object> getApplyDeposit(@RequestParam Long id,@RequestParam BigDecimal num) throws BusinessException {
        // 数据校验
        if (StringUtils.isEmpty(id)||StringUtils.isEmpty(num)){
            throw new BusinessException(ExceptionCode.NO_PARAM);
        }
        // 提现操作
        userService.withdraw(id, num);
        JsonResult jsonResult = new JsonResult();
        jsonResult.setCode("200");
        jsonResult.setMsg("提现申请成功");
        return jsonResult.getDataMap();
    }

}
